package xiao.ke.sbdemo.controller;/**
 * @author XuXiaoK
 * @create 2019-11-25 23:35
 */

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import xiao.ke.sbdemo.model.JsonData;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 *@Author XiaoKe
 *@Date 2019/11/25 23:35
 *@Description TODO
 */
@Controller
public class FileController {

    public static final String filePath = "D:/IdeaWorkspace1/springbootdemo/src/main/resources/static";

    @RequestMapping("upload")
    @ResponseBody
    public JsonData upload(@RequestParam("head_img") MultipartFile file, HttpServletRequest request) {

        String name = request.getParameter("name");
        System.out.println(name);

        String filename = file.getOriginalFilename();
        System.out.println(filename);

        String s = filename.substring(filename.lastIndexOf("."));
        System.out.println(s);

        filename = UUID.randomUUID() + s;
        System.out.println(filename);

        File file1 = new File(filePath + filename);

        try {
            file.transferTo(file1);

            return new JsonData(0, filename);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new JsonData(-1, "fail", null);
    }
}
